using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace HelloCube.Aspects
{
    /*
     * 使用Aspect来封装一些操作，执行在主线程上
     */
    public partial struct RotationSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.Aspects>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            float deltaTime = SystemAPI.Time.DeltaTime;
            double elapsedTime = SystemAPI.Time.ElapsedTime;

            foreach (var (transform, rotateSpeed) in SystemAPI.Query<RefRW<LocalTransform>, RefRO<RotateSpeed>>())
            {
                transform.ValueRW = transform.ValueRO.RotateY(rotateSpeed.ValueRO.RadiansPerSecond * deltaTime);
            }

            foreach (var verticalMovement in SystemAPI.Query<VerticalMovementAspect>())
            {
                verticalMovement.Move(elapsedTime);
            }
        }
    }

    readonly partial struct VerticalMovementAspect : IAspect
    {
        readonly RefRW<LocalTransform> mTransform;
        readonly RefRO<RotateSpeed> mRotateSpeed;

        public void Move(double elapsedTime)
        {
            mTransform.ValueRW.Position.y = (float)math.sin(elapsedTime * mRotateSpeed.ValueRO.RadiansPerSecond);
        }
    }
}